package org.meruvian.yama.action;

import javax.inject.Inject;

import org.apache.struts2.interceptor.validation.SkipValidation;
import org.meruvian.inca.struts2.rest.annotation.Action;
import org.meruvian.inca.struts2.rest.annotation.Action.HttpMethod;
import org.meruvian.inca.struts2.rest.annotation.Result;
import org.meruvian.inca.struts2.rest.annotation.Results;
import org.meruvian.yama.actions.DefaultAction;
import org.meruvian.yama.service.ItemService;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

@Action(name = "/module/item")
@Results({
		@Result(name = DefaultAction.SUCCESS, type = "redirect", location = "/module/item?success"),
		@Result(name = DefaultAction.INPUT, type = "freemarker", location = "/view/item/form.ftl"),
		@Result(name = DefaultAction.INDEX, type = "freemarker", location = "/view/item/list.ftl") })
public class ItemAction extends DefaultAction implements
		ModelDriven<ItemActionModel> {

	private ItemActionModel model = new ItemActionModel();

	@Inject
	private ItemService itemService;

	@SkipValidation
	@Action(name = "add", method = HttpMethod.GET)
	public String form() {
		return INPUT;
	}

	@Action(name = "add", method = HttpMethod.POST)
	@Validations(requiredStrings = { @RequiredStringValidator(fieldName = "item.name", message = "Name cannot be blank", trim = true) })
	public String save() {
		itemService.saveItem(model.getItem());

		return SUCCESS;
	}

	@SkipValidation
	@Action
	public String execute() {

		String name = model.getQ();
		name = name == null ? "" : name;

	    model.setItems(itemService.findItems(name,model.getMax(), null, "",	model.getPage() - 1));
		return INDEX;
	}

	@Action(name = "edit/{q}", method = HttpMethod.GET)
	@SkipValidation
	public String edit() {
		model.setItem(itemService.getItemsById(model.getQ()));

		return INPUT;
	}

	public ItemActionModel getModel() {
		return model;
	}

	

}
